//
//  YunPlatform.m
//  reSearchDemo
//
//  Created by 云库 on 15/7/24.
//  Copyright (c) 2015年 Kiwaro. All rights reserved.
//

#import "YunPlatform.h"
#import "MenuView.h"
#import "PlatformCell.h"
#import "MenuView.h"
#import "LoginYunPlaVC.h"
#import "UserManagement.h"
#import "PlatformFunction.h"
#import "PlatformManagement.h"
#import "PlatformMerchantsVC.h"
#import "PlatformMy.h"
#import "SecurityCenter.h"
#import "PlatformUserManagement.h"

#import "Session.h"
#import "Notify.h"
#import "Room.h"
#import "SessionNewController.h"
#import "TalkingViewController.h"
#import "SessionCell.h"
#import "Message.h"
#import "AppDelegate.h"
#import "UserInfoViewController.h"
#import "UIImage+FlatUI.h"
#import "UIImage+Resize.h"
#import "Globals.h"
#import "CameraActionSheet.h"
#import "JSON.h"
#import "SubSessionViewController.h"
@interface YunPlatform ()<BSTableViewDataSource, CameraActionSheetDelegate>{
    UIView * actionBar;
    MenuView * _menuView;
    UIView *BGMenuView;
    NSMutableArray *_indexArr;   /**< 保存btn点击状态 */
    
    UIButton * _userCommunication;
    UIButton * _userManager;
    
    NSMutableArray *UserData;  /**< 关注平台用户的数组 */
    UITableView *_tableView;
    UIBarButtonItem *UserBtn;
    UIBarButtonItem *MoreBtn;
    
}
@property(nonatomic,retain)MenuView * menuView;

@end

@implementation YunPlatform

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    self.title = @"消息";
//    [self setRightBarButtonImage:LOADIMAGE(@"btn_more") highlightedImage:nil selector:@selector(menu)];
    needToLoad = NO;
    
    MoreBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_more"] style:UIBarButtonItemStyleDone target:self action:@selector(BtnAction:)];
    UserBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"User_1"] style:UIBarButtonItemStyleDone target:self action:@selector(BtnAction:)];
    UIBarButtonItem *navi = [[UIBarButtonItem alloc] init];
    NSArray *ItemArr = [NSArray arrayWithObjects:navi,MoreBtn,UserBtn,navi, nil];
    
    self.navigationItem.rightBarButtonItems = ItemArr;
    
    [self buildMainView];
    
    _indexArr = [NSMutableArray arrayWithObjects:@"NO",@"NO",@"NO",@"NO",@"NO", nil];
    
//    UserData = [NSMutableArray arrayWithArray:[UIFont familyNames]];
    
    //获取平台消息
    
//    [[HTTPGlobals shareHTTPGlobal] GetHTTPRequest:@"MobilePort/Message/index.html" parameters:nil finish:^(BOOL seccess, NSString *error, id obj) {
//        if (seccess) {
//            DLog(@"消息请求成功!");
//            DLog(@"obj = %@",obj);
//            NSArray *arr = obj[@"data"][@"data"];
//            DLog(@"arr = %@",arr);
//            DLog(@"__huifu = %@",arr[0][@"huifu"]);
//            NSArray *arr1 = arr[0][@"huifu"];
//            for (NSDictionary *dic in arr) {
//                NSArray *_arr = dic[@"huifu"];
//                for (NSDictionary *subDic in _arr) {
//                    DLog(@"subactiontime = %@",subDic[@"actiontime"]);
//                    DLog(@"subcontent = %@",subDic[@"content"]);
//                    DLog(@"subnickname = %@",subDic[@"nickname"]);
//                    DLog(@"subtypefile = %@",subDic[@"typefile"]);
//                    
//                }
//                DLog(@"__actiontime = %@",dic[@"actiontime"]);
//                DLog(@"__content = %@",dic[@"content"]);
//                DLog(@"__count = %d",_arr.count);
//            }
//            DLog(@"__huifu.count = %ld",arr1.count);
//            DLog(@"arr.count = %d",arr.count);
////            for (NSDictionary *dic in arr) {
////                DLog(@"actiontime = %@",dic[@"actiontime"]);
////                DLog(@"content = %@",dic[@"content"]);
////                DLog(@"from = %@",dic[@"from"]);
////                DLog(@"nickname = %@",dic[@"nickname"]);
////            }
//        }
//    }];
    
    
}
//导航栏按钮事件
-(void)BtnAction:(UIBarButtonItem *)sender {
    if (sender == UserBtn) {
        [self pushViewController:[PlatformUserManagement new]];
        return;
    }
    NSArray * arr = nil;
    arr = @[@"退出登录", @"安全中心"];
    _menuView = [[MenuView alloc] initWithButtonTitles:arr withDelegate:self];
    _menuView.hasImage = NO;
    [_menuView showInView:self.view origin:CGPointMake(self.view.width - 180, 70)];
    _menuView.buttonView.delegate=self;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self forwardMessageIfHas];
    [contentArr removeAllObjects];
    [contentArr addObjectsFromArray:[Session getListFromDBWithIsTop]];
    [tableView reloadData];
}
- (void)loginSuccess {
    self.navigationItem.title = @"消息";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subPlatBadgeChange:) name:@"SubPlatBadgeChange" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedMessage:) name:@"receivedMessage" object:nil];
    //注册重置谈话的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reSetConversation:) name:@"reSetConversation" object:nil];
    //注册更新备注名的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUIForMarkName:) name:@"updateUIForMarkName" object:nil];
    //注册群消息处理的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedNotifyGroupChat:) name:@"receivedNotifyGroupChat" object:nil];
    [contentArr addObjectsFromArray:[Session getListFromDBWithIsTop]];
    [self setbadgeValue:[self getUnreadCount]];
    [tableView reloadData];
}
- (int)getUnreadCount {
    int unreadCount = 0;
    for (Session * item in contentArr) {
        unreadCount += item.unreadCount;
    }
    return unreadCount;
}
/** 收到更新备注名的通知后重加载列表 */
- (void)updateUIForMarkName:(NSNotification*)sender {
    [contentArr removeAllObjects];
    [contentArr addObjectsFromArray:[Session getListFromDBWithIsTop]];
    [tableView reloadData];
}

/** 群消息通知的处理 */
- (void)receivedNotifyGroupChat:(NSNotification*)sender {
    Notify * ntf = sender.object;
    if (ntf.type == forNotifyDestroyRoom || ntf.type == forNotifyKickUser) {
        BOOL needDeleted = NO;
        if (ntf.type == forNotifyDestroyRoom) {
            needDeleted = YES;
        } else if (ntf.type == forNotifyKickUser && [ntf.user.uid isEqualToString:[BSEngine currentUserId]]) {
            needDeleted = YES;
        }
        if (needDeleted) {
            __block NSInteger find = -1;
            [contentArr enumerateObjectsUsingBlock:^(Session *obj, NSUInteger idx, BOOL *stop) {
                if ([obj.uid isEqualToString:ntf.roomID]) {
                    Room * room = [Room roomForUid:obj.uid];
                    if (room) {
                        [room deleteFromDB];
                    }
                    [obj deleteFromDB];
                    find = idx;
                    *stop = YES;
                }
            }];
            if (find >= 0) {
                [contentArr removeObjectAtIndex:find];
                [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:find inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            }
        }
    } else if (ntf.type == forNotifyGroupInfoUpdate) {
        // 群昵称更改
        [contentArr enumerateObjectsUsingBlock:^(Session *obj, NSUInteger idx, BOOL *stop) {
            if ([obj.uid isEqualToString:ntf.roomID]) {
                obj.name =
                obj.message.toname = ntf.roomName;
                [obj.message updateVaule:ntf.roomName key:@"toname"];
                [obj updateVaule:obj.name key:@"name"];
                [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                *stop = YES;
            }
        }];
    }
}
/** 重加载会话列表 */
- (void)cleanMessageWithSession:(Session*)item {
    [contentArr removeAllObjects];
    [contentArr addObjectsFromArray:[Session getListFromDBWithIsTop]];
    [tableView reloadData];
}

/** 废弃函数 现用于强制刷新列表*/
- (void)forwardMessageIfHas {
    if (isFirstAppear) {
        [tableView reloadData];
    }
}
#pragma mark -
#pragma mark - Messages
/* 合并订阅号新闻 */
- (void)hanldeSystemNews:(NSString *)content{
    NSString *alert = content;
    NSRange range = [alert rangeOfString:@"[系统新闻,"];
    if (range.location!=NSNotFound) {
        
        // [系统名称,标题,跳转url]内容
        NSString *content = [alert stringByReplacingOccurrencesOfString:@"[系统新闻," withString:@""];
        NSArray *array = [content componentsSeparatedByString:@"]"];
        if (array.count>1) {
            NSArray *config = [array[0] componentsSeparatedByString:@","];
            if (config.count == 2) {
                NSDictionary *dict = @{@"title":config[0],@"url":config[1],@"date":[NSDate date],@"uid":@"1239421121122209"};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"GASystemNews"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                Message *message = [[Message alloc] init];
                message.content = dict[@"title"];
                message.typefile = forFileText;
                message.typechat = forChatTypeUser;
                message.sendTime = [NSString stringWithFormat:@"%.0f",[dict[@"date"] timeIntervalSince1970] * 1000];
                message.uid = dict[@"uid"];
                [message insertDB];
                
                Session *oldSession = [Session getSessionWithID:dict[@"uid"]];
                if (oldSession) {
                    [oldSession deleteFromDB];
                }oldSession = [Session getSessionWithID:dict[@"uid"]];
                if (oldSession) {
                    [oldSession deleteFromDB];
                }
                
                Session *news = [Session sessionWithMessage:message];
                news.uid = dict[@"uid"];
                news.name = @"系统新闻";
                news.typechat = forChatTypeUser;
                news.unreadCount = 1;
                news.istop = NO;
                [news insertDB];
            }
        }
    }
}
/** 单聊消息通知的处理 */
- (void)receivedMessage:(NSNotification*)sender {
    Message * msg = sender.object;
    if (msg.typechat == forChatTypeMeet) {
        return;
    }
    
    __block Session * itemS = nil;
    if (msg.typechat == forChatTypeSubChat) {
        //插入订阅号的session
        Session *subSession = [Session getSessionWithID:msg.withID];
        if (nil==subSession) {
            subSession = [Session sessionWithMessage:msg];
            subSession.isSubPlat = YES;
            [subSession insertDB];
        }else{
            [subSession updateWithMessage:msg];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"didSaveSubMessage" object:msg];
        
        
        Message *newMSG = [msg copy];
        //订阅号固定SessionID
        newMSG.uid = @"9110211";
        newMSG.isSendByMe = msg.isSendByMe;
        newMSG.displayName = msg.displayName;
        
        if (newMSG.isSendByMe && !newMSG.displayName) {
            newMSG.displayName = msg.toname;
        }
        
        newMSG.toId = @"9110211";
        newMSG.fromId = @"9110211";
        
        //订阅号固定SessionID
        __block NSInteger index;
        [contentArr enumerateObjectsUsingBlock:^(Session * ssion, NSUInteger idx, BOOL *stop) {
            NSString * str = ssion.uid;
            if ([str isEqualToString:newMSG.fromId]) {
                itemS = ssion;
                index = idx;
                *stop = YES;
            }
        }];
        
        if (itemS == nil) {
            //新会话
            itemS = [Session sessionWithMessage:newMSG];
            itemS.isSubPlat = NO;
            itemS.name = @"云传播平台";
            itemS.unreadCount = 1;
            itemS.typechat = forChatTypeSubChat;
            [itemS insertDB];
            [itemS justUpdateWithMessage:newMSG];
        } else {
            //更新原有会话
            if (nil==newMSG.displayName) {
                newMSG.displayName = itemS.message.displayName;
            }
            itemS.name = @"云传播平台";
            itemS.typechat = forChatTypeSubChat;
            [itemS updateWithMessage:newMSG];
        }
        
        //存储msg
        [newMSG insertDB];
    }
    else{
        __block NSInteger index;
        [contentArr enumerateObjectsUsingBlock:^(Session * ssion, NSUInteger idx, BOOL *stop) {
            NSString * str = ssion.message.withID;
            if ([str isEqualToString:msg.withID]) {
                itemS = ssion;
                index = idx;
                *stop = YES;
            }
        }];
        
        if (!msg.isSendByMe && !msg.displayName) {
            User *user = [User userWithID:msg.fromId];
            msg.displayName = user.displayName;
        }
        
        if (itemS == nil) {
            //新会话
            itemS = [Session sessionWithMessage:msg];
            [itemS insertDB];
            [itemS justUpdateWithMessage:msg];
        } else {
            //更新原有会话
            [itemS updateWithMessage:msg];
        }
    }
    
    // 重新分配 cell 的 indexpath
    [contentArr removeAllObjects];
    [contentArr addObjectsFromArray:[Session getListFromDBWithIsTop]];
    [tableView reloadData];
    [self setbadgeValue:[self getUnreadCount]];
}
/** 重置消息数量 */
- (void)reSetConversation:(NSNotification*)sender {
    NSString* withID = sender.object;
    //    DLog(@"%s:%@",__FUNCTION__,withID);
    if (withID) {
        for (int i = 0; i < contentArr.count; i++) {
            Session* cs = [contentArr objectAtIndex:i];
            if ([cs.uid isEqualToString:withID]) {
                if (cs.unreadCount > 0) {
                    [cs resetUnread];
                    [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                break;
            }
        }
    }
    [self setbadgeValue:[self getUnreadCount]];
}

/** 设置程序app 的applicationIconBadgeNumber*/
- (void)setbadgeValue:(int)value {
    NSString *str = nil;
    if (value > 0) {
        str = [NSString stringWithFormat:@"%d", value];
    } else {
        str = nil;
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = value;
    self.tabBarItem.badgeValue = str;
    [[AppDelegate instance] refreshNewChatMessage:value];
}

- (void)subPlatBadgeChange:(NSNotification *)noti{
    
    NSInteger newValue = [noti.object integerValue];
    Session *sesion = [Session getSessionWithID:@"9110211"];
    sesion.unreadCount = newValue-1;
    [sesion updateWithMessage:sesion.message];
    // 重新分配 cell 的 indexpath
    [contentArr removeAllObjects];
    [contentArr addObjectsFromArray:[Session getListFromDBWithIsTop]];
    [tableView reloadData];
    [self setbadgeValue:[self getUnreadCount]];
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)sender heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (sender == _menuView.buttonView) {
        return 42;
    }
    else {
        //to be impletemented in sub-class
        return self.tableViewCellHeight;
    }
    
}
- (UITableViewCell*)tableView:(UITableView *)sender cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* CellIdentifier = @"SessionCell";
    SessionCell * cell = [sender dequeueReusableCellWithIdentifier:CellIdentifier];
    if (inFilter) {
        if (!cell) {
            cell = [[SessionCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            [cell enableLongPress];
        }
    } else {
        if (!cell) {
            cell = [[SessionCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            [cell enableLongPress];
        }
    }
    cell.superTableView = sender;
    
    Session * itemS = [self.dataArray objectAtIndex:indexPath.row];
    cell.withItem = itemS;
    if (itemS.isRoom) {
        // 群聊的头像是用户头像拼出来的
        if (!itemS.value) {
            itemS.value = [itemS.headsmall componentsSeparatedByString:@","];
        }
        NSInteger number = [itemS.value count];
        if (number > 4) {
            number = 4;
        }
        [cell setNumberOfGroupHead:number];
    } else {
        [cell setNumberOfGroupHead:0];
    }
    [cell setBottomLine:NO];
    if (indexPath.row == contentArr.count - 1) {
        [cell setBottomLine:YES];
    }
    
    [cell update:^(NSString *name) {
        [cell autoAdjustText];
        cell.labTime.left = SCREEN_WIDTH-cell.labTime.width-10;
        cell.textLabel.width = cell.width - 50 - cell.labTime.width;
        if (itemS.istop) {
            cell.contentView.backgroundColor =
            cell.backgroundColor = RGBACOLOR(204, 204, 204, 0.6);
        } else {
            cell.contentView.backgroundColor =
            cell.backgroundColor = [UIColor whiteColor];
        }
    }];
    return cell;
}

- (void)tableView:(id)sender handleTableviewCellLongPressed:(NSIndexPath*)indexPath {
    Session * item = [contentArr objectAtIndex:indexPath.row];
    CameraActionSheet * sheet = [[CameraActionSheet alloc] initWithActionTitle:nil TextViews:nil CancelTitle:@"取消" withDelegate:self otherButtonTitles:item.istop?@"取消置顶":@"置顶聊天", @"删除聊天", nil];
    sheet.idx = [NSString stringWithFormat:@"%d", (int)indexPath.row];
    [sheet show];
}

- (void)tableView:(UITableView *)sender didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [sender deselectRowAtIndexPath:indexPath animated:YES];
    if (sender == _menuView.buttonView) {
        [_menuView hide];
        switch (indexPath.row) {
            case 0:
            {
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[LoginYunPlaVC class]]) {
                        LoginYunPlaVC *LoginVC = (LoginYunPlaVC *)controller;
                        [self.navigationController popToViewController:LoginVC animated:YES];
                    }
                }
                break;
            }
            case 1:
            {
                [self.navigationController pushViewController:[SecurityCenter new] animated:YES];
                break;
            }
            default:
                break;
        }

    }else {
        Session * item = [contentArr objectAtIndex:indexPath.row];
        if ([item.uid isEqualToString:@"9110211"]) {
            id con = [[SubSessionViewController alloc] init];
            [self pushViewController:con];
        }else{
            item.unreadCount = 0;
            [self setbadgeValue:[self getUnreadCount]];
            id con = [[TalkingViewController alloc] initWithSession:item];
            [self pushViewController:con];
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
    
}

- (void)tableView:(id)sender didTapHeaderAtIndexPath:(NSIndexPath *)indexPath {
    Session* itemS = [self.dataArray objectAtIndex:indexPath.row];
    if (itemS.isRoom) {
        
    }else if (itemS.typechat == forChatTypeSubChat) {
        
    }else if (itemS.typechat == forChatTypeServiceChat) {
        [self getCloudUserByID:itemS.uid];
    }
    else{
        [self getUserByName:itemS.uid];
    }
}

- (void)tableView:(UITableView *)sender willDisplayCell:(SessionCell*)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (sender == _menuView.buttonView) {
        return;
    }
    Session* item = [self.dataArray objectAtIndex:indexPath.row];
    if (item.isRoom) {
        cell.imageView.image = [Globals getImageRoomHeadDefault];
    }else {
        cell.imageView.image = [Globals getImageUserHeadDefault];
    }
    NSInvocationOperation * opHeadItem = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadHeadImageWithIndexPath:) object:indexPath];
    [baseOperationQueue addOperation:opHeadItem];
}

- (NSString*)baseTableView:(UITableView *)sender imageURLAtIndexPath:(NSIndexPath *)indexPath {
    Session * item = [self.dataArray objectAtIndex:indexPath.row];
    if (item.isRoom) {
        return item.value;
    }else {
        return item.headsmall;
    }
}

- (int)baseTableView:(UITableView *)sender imageTagAtIndexPath:(NSIndexPath*)indexPath {
    Session * item = [self.dataArray objectAtIndex:indexPath.row];
    if (item.isRoom) {
        return -2;
    } else {
        return -1;
    }
}

- (void)baseTableView:(NSInteger)tag imageUpdateAtIndexPath:(NSIndexPath*)indexPath image:(UIImage *)image idx:(NSInteger)idx {
    if (tag == -1) {
        [self setHeadImage:image forIndex:indexPath];
    } else {
        [self setGroupHeadImage:image forIndex:indexPath forPos:idx];
    }
}

- (void)kwAlertView:(id)sender didDismissWithButtonIndex:(NSInteger)index {
    if (index == 0) {
        [[AppDelegate instance] signOut];
    }
}

#pragma mark - CameraActionSheetDelegate

- (void)cameraActionSheet:(CameraActionSheet *)sender didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 2) {
        return;
    }
    Session * session = contentArr[sender.idx.intValue];
    if (buttonIndex == 0) {
        // 更新置顶聊天状态
        if (session.istop > 0) {
            session.istop = 0;
        } else {
            session.istop = [Session getLastTopSession]+1;
        }
        [session updateVaule:[NSNumber numberWithInt:session.istop] key:@"istop"];
        [self cleanMessageWithSession:session];
    } else {
        // 删除某个会话， 更新数据库
        [session deleteFromDB];
        [contentArr removeObjectAtIndex:sender.idx.intValue];
        [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:sender.idx.intValue inSection:0]] withRowAnimation:UITableViewRowAnimationRight];
        [self setbadgeValue:[self getUnreadCount]];
    }
}



-(void)buildMainView{
    /*
    _userCommunication=[UIButton buttonWithType:UIButtonTypeCustom];
    _userCommunication.frame=CGRectMake(0, 64, self.view.frame.size.width/2, 30);
    _userCommunication.backgroundColor=[UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:0.9];
    _userCommunication.selected = YES;
    [_userCommunication setTitle:@"用户交流" forState:UIControlStateNormal];
    [_userCommunication setTitle:@"用户交流" forState:UIControlStateSelected];
    [_userCommunication setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_userCommunication setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [_userCommunication addTarget:self action:@selector(userCommunication:) forControlEvents:UIControlEventTouchUpInside];
    _userCommunication.tintColor=[UIColor blackColor];
    [self.view addSubview:_userCommunication];
    
    _userManager=[UIButton buttonWithType:UIButtonTypeCustom];
    _userManager.frame=CGRectMake(self.view.frame.size.width/2, 64, self.view.frame.size.width/2, 30);
    _userManager.backgroundColor=[UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:0.9];
    _userManager.selected = NO;
    [_userManager setTitle:@"用户管理" forState:UIControlStateNormal];
    [_userManager setTitle:@"用户管理" forState:UIControlStateSelected];
    [_userManager setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_userManager setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [_userManager addTarget:self action:@selector(userManager:) forControlEvents:UIControlEventTouchUpInside];
    _userManager.tintColor=[UIColor blackColor];
    [self.view addSubview:_userManager];
     */
     
//    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, _userManager.frame.origin.y+_userManager.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-_userManager.frame.origin.y+_userManager.frame.size.height)];
//    _tableView.delegate=self;
//    _tableView.dataSource=self;
//    _tableView.rowHeight=100;
//    _tableView.tag=120;
//    _tableView.tableFooterView = [[UIView alloc] init];
//    [_tableView registerClass:[PlatformCell class] forCellReuseIdentifier:@"cell"];
//    [self.view addSubview:_tableView];
    
    UIButton * bottomMess=[UIButton buttonWithType:UIButtonTypeSystem];
    bottomMess.frame=CGRectMake(0, self.view.frame.size.height-44, self.view.frame.size.width/5, 44);
    bottomMess.backgroundColor=[UIColor grayColor];
    bottomMess.tintColor=[UIColor blackColor];
    [bottomMess setTitle:@"消息" forState:UIControlStateNormal];
    [bottomMess addTarget:self action:@selector(bottomMessClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomMess];
    UIButton * bottomFunc=[UIButton buttonWithType:UIButtonTypeSystem];
    bottomFunc.backgroundColor=[UIColor grayColor];
    bottomFunc.tintColor=[UIColor blackColor];
    bottomFunc.frame=CGRectMake(self.view.frame.size.width/5, self.view.frame.size.height-44, self.view.frame.size.width/5, 44);
    [bottomFunc setTitle:@"功能" forState:UIControlStateNormal];
    [bottomFunc addTarget:self action:@selector(bottomFunc:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomFunc];
    UIButton *bottomMana=[UIButton buttonWithType:UIButtonTypeSystem];
    bottomMana.frame=CGRectMake(self.view.frame.size.width/5*2, self.view.frame.size.height-44, self.view.frame.size.width/5, 44);
    [bottomMana setTitle:@"管理" forState:UIControlStateNormal];
    [bottomMana addTarget:self action:@selector(bottomMana:) forControlEvents:UIControlEventTouchUpInside];
    bottomMana.backgroundColor=[UIColor grayColor];
    bottomMana.tintColor=[UIColor blackColor];
    [self.view addSubview:bottomMana];
    
    UIButton *bottomMerchants = [UIButton buttonWithType:UIButtonTypeSystem];
    bottomMerchants.frame = CGRectMake(self.view.frame.size.width/5*3, self.view.frame.size.height - 44, self.view.frame.size.width/5, 44);
    [bottomMerchants setTitle:@"商家" forState:0];
    [bottomMerchants addTarget:self action:@selector(bottomMerchants:) forControlEvents:UIControlEventTouchUpInside];
    bottomMerchants.backgroundColor = [UIColor grayColor];
    bottomMerchants.tintColor = [UIColor blackColor];
    [self.view addSubview:bottomMerchants];
    
    UIButton *bottomMy = [UIButton buttonWithType:UIButtonTypeSystem];
    bottomMy.frame = CGRectMake(self.view.frame.size.width/5*4, self.view.frame.size.height - 44, self.view.frame.size.width/5, 44);
    [bottomMy setTitle:@"我的" forState:0];
    [bottomMy addTarget:self action:@selector(bottomMy:) forControlEvents:UIControlEventTouchUpInside];
    bottomMy.backgroundColor = [UIColor grayColor];
    bottomMy.tintColor = [UIColor blackColor];
    [self.view addSubview:bottomMy];
}
#pragma mark - ButtonClickMethod
//点击用户交流btn执行的函数
-(void)userCommunication:(UIButton*)sender{
    sender.selected = YES;
    _userManager.selected = NO;
    [_tableView reloadData];
    
}
//点击用户管理btn执行的函数
-(void)userManager:(UIButton*)sender{
    sender.selected = YES;
    _userCommunication.selected = NO;
    [_tableView reloadData];
//    [self pushViewController:[UserManagement new]];
}
//点击消息btn执行的函数
-(void)bottomMessClick:(UIButton*)sender{
    }
//点击功能btn执行的函数
-(void)bottomFunc:(UIButton*)sender{
    /*
    if (BGMenuView) {
        [self removeBGMenuView];
        return;
    }
    NSArray *functionArr = @[@"群发功能",@"群发历史",@"自动回复",@"菜单管理",@"文章分类",@"文章发布",@"文章管理"];
    BGMenuView= [[UIView alloc] init];
    BGMenuView.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y, sender.frame.size.width, 0);
    BGMenuView.backgroundColor = [UIColor lightGrayColor];
    for (NSInteger i = 0; i < functionArr.count; i++) {
        UIButton *Fun_btn = [UIButton buttonWithType:UIButtonTypeSystem];
        Fun_btn.frame = CGRectMake(sender.frame.origin.x - sender.frame.size.width, self.view.frame.size.width - sender.frame.size.height - 40*(i+1), sender.frame.size.width, 40);
        [Fun_btn setTitle:functionArr[i] forState:0];
        [Fun_btn setTitleColor:[UIColor blackColor] forState:0];
        Fun_btn.tag = 1000+i;
        [Fun_btn addTarget:self action:@selector(FunctionMenuAction:) forControlEvents:UIControlEventTouchUpInside];
        [BGMenuView addSubview:Fun_btn];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(BGMenuViewTapAction:)];
    
    [self.view addGestureRecognizer:tap];
    [self.view addSubview:BGMenuView];
    
    [UIView animateWithDuration:0.3 animations:^{
        BGMenuView.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y - 280, sender.frame.size.width, 280);
        
    } completion:^(BOOL finished) {
        
    }];
     */
    [self pushViewController:[PlatformFunction new]];
    
}
//点击管理btn执行的函数
-(void)bottomMana:(UIButton*)sender{
    /*
    if (BGMenuView) {
        [self removeBGMenuView];
        return;
    }
    NSArray *ManaArr = @[@"发布产品",@"产品管理",@"订单管理",@"企业钱包"];
    BGMenuView= [[UIView alloc] init];
    DLog(@"______%f",sender.frame.origin.y);
    DLog(@"y = %f",self.view.frame.size.height - 44);
    BGMenuView.frame = CGRectMake(sender.frame.origin.x, self.view.frame.size.height - 44, sender.frame.size.width, 44);
    BGMenuView.backgroundColor = [UIColor lightGrayColor];
    for (NSInteger i = 0; i < ManaArr.count; i++) {
        UIButton *Mana_btn = [UIButton buttonWithType:UIButtonTypeSystem];
        Mana_btn.frame = CGRectMake(0, 160 - 40*(i+1), sender.frame.size.width, 40);
        [Mana_btn setTitle:ManaArr[i] forState:0];
        [Mana_btn setTitleColor:[UIColor blackColor] forState:0];
        Mana_btn.tag = 1000+i;
        [Mana_btn addTarget:self action:@selector(FunctionMenuAction:) forControlEvents:UIControlEventTouchUpInside];
        [BGMenuView addSubview:Mana_btn];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(BGMenuViewTapAction:)];
    
    [self.view addGestureRecognizer:tap];
    [self.view addSubview:BGMenuView];
    
    [UIView animateWithDuration:0.3 animations:^{
        BGMenuView.frame = CGRectMake(sender.frame.origin.x, sender.frame.origin.y - 160, sender.frame.size.width, 160);
        
    } completion:^(BOOL finished) {
        
    }];
     */
    [self pushViewController:[PlatformManagement new]];
    
}
//点击商家btn执行的函数
-(void)bottomMerchants:(UIButton *)sender {
    [self pushViewController:[PlatformMerchantsVC new]];
}
//点击我的btn执行的函数
-(void)bottomMy:(UIButton *)sender {
    [self pushViewController:[PlatformMy new]];
}

//弃用
-(void)FunctionMenuAction:(UIButton *)sender {
    DLog(@"点击菜单按钮!");
    [self removeBGMenuView];
}

-(void)BGMenuViewTapAction:(UITapGestureRecognizer *)sender {
    
    [self removeBGMenuView];
    
}
/** 移除背景视图*/
-(void)removeBGMenuView {
    
    [UIView animateWithDuration:0.3 animations:^{
        BGMenuView.frame = CGRectMake(BGMenuView.frame.origin.x, self.view.frame.size.height - 44, BGMenuView.frame.size.width, 0);
    } completion:^(BOOL finished) {
        [BGMenuView removeFromSuperview];
        BGMenuView = nil;
        
    }];
}

#pragma mark -
#pragma mark --初始化弹出菜单函数--
-(void)Btnmenu:(NSArray *)TitleArr ID:(UIButton *)sender {
    if (_menuView) {
        [_menuView hide];
    }
    _menuView = [[MenuView alloc] initWithButtonTitles:TitleArr withDelegate:self];
    _menuView.hasImage = NO;
    [_menuView showInView:self.view origin:CGPointMake(sender.frame.origin.x, 70)];
    _menuView.backgroundView.top = sender.frame.origin.y - 200;
    _menuView.buttonView.delegate = self;
}

-(void)menu{
    if (_menuView) {
        [_menuView hide];
    }
    NSArray * arr=@[@"退出登录",@"平台设置",@"平台认证",@"开发中心",@"修改平台密码",@"常见问题",];
    _menuView = [[MenuView alloc] initWithButtonTitles:arr withDelegate:self];
    _menuView.hasImage = NO;
    [_menuView showInView:self.view origin:CGPointMake(self.view.width - 180, 70)];
    _menuView.buttonView.delegate=self;
}
/*
#pragma mark - UITableViewDelegate&UITableViewDataSourse
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
   
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PlatformCell * cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.dataSourse=@"";
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag==120) {
           return 100;
    }else{
        return 42;
    }
 
}
 */
/*
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView.tag==120) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }else{
        [_menuView hide];
        switch (indexPath.row) {
            case 0:
            {
                for (UIViewController *controller in self.navigationController.viewControllers) {
                    if ([controller isKindOfClass:[LoginYunPlaVC class]]) {
                        LoginYunPlaVC *LoginVC = (LoginYunPlaVC *)controller;
                        [self.navigationController popToViewController:LoginVC animated:YES];
                    }
                }
               break;
            }
            case 1:
            {
                [self.navigationController pushViewController:[SecurityCenter new] animated:YES];
                break;
            }
            case 2:
            {
                break;
            }
            case 3:
            {
                break;
            }
            case 4:
            {
                break;
            }
            case 5:
            {
                break;
            }
                
            default:
                break;
        }
    }

}
 */

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
